package com.gbase8c.dmt.migration.job;

import com.gbase8c.dmt.migration.MoLogger;
import com.gbase8c.dmt.model.enums.MigrationObjectType;
import com.gbase8c.dmt.model.migration.dto.MigrationObject;
import com.gbase8c.dmt.model.migration.record.JobThreadRecord;
import com.gbase8c.dmt.model.enums.Status;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

@Slf4j
public class TableSpaceJobThread extends AbstractJobThread{

    public TableSpaceJobThread(MigrationObjectType type, MigrationObject dbObject, DataSource tarDataSource, MoLogger moLogger) {
        super(type, dbObject, tarDataSource, moLogger);
    }

    @Override
    public JobThreadRecord call() throws Exception {
        JobThreadRecord jobThreadRecord = new JobThreadRecord();
        List<String> contents = dbObject.getContents();
//        String schema = (String) Reflections.invokeGetter(dbObject, "tableSpaceName");
        String schema = "other";
        QueryRunner queryRunner = new QueryRunner(this.tarDataSource);
        jobThreadRecord.setSchemaName(schema);
        try {
            for (String sql:contents){
                int execute = queryRunner.execute(sql);
                log.info("sql:{} \n 执行结果: {}",sql,execute);
            }
            jobThreadRecord.setFlag(true);
            dbObject.setStatus(Status.Finished);
        }catch (SQLException exception) {
            jobThreadRecord.setFlag(false);
            dbObject.setMsg(exception.getMessage());
            dbObject.setStatus(Status.Failure);
            jobThreadRecord.setErrorLog(exception.getMessage());
        }
        jobThreadRecord.setDbObject(dbObject);
        return jobThreadRecord;
    }
}
